#!/usr/bin/env python
"""return weather data from the Google weather API"""
import urllib2, sys, optparse, re
from xml.etree import ElementTree as et

def icon_download(tree, filename):
	"""icon_download - download weather.gif from google"""
	link=tree.find("weather/current_conditions/icon").attrib['data']
	myfile=open(filename, 'wb')
	try:
		iconurl="http://www.google.com%s" % link
		f=urllib2.urlopen(iconurl)
		myfile.write(f.read())
	except:
		myfile.close()
		pass

def header(tree):
	"""header - return header with city, st"""
	return "Weather status for %s:\n" % tree.find("weather/forecast_information/city").attrib['data']

def four_day_forecast(tree):
	"""four_day_forcast - return four day forecast info"""
	retlist=[]
	for i in range(len(tree.findall("weather/forecast_conditions"))):
		for element in tree.findall("weather/forecast_conditions")[i]:
			if element.tag == 'day_of_week':
 				dow=element.attrib['data']
			elif element.tag == 'high':
                                htemp=element.attrib['data']
                        elif element.tag == 'low':
                                ltemp=element.attrib['data']
                        elif element.tag == 'condition':
                                condition=element.attrib['data']
		retlist.append("%s:\nCondition: %s\nHigh: %s\nLow: %s\n" % (dow, condition, htemp, ltemp))
 	return retlist	

def current_condition(tree):
	"""current_condition - current weather condition data"""
	for element in tree.find("weather/current_conditions"):
		if element.tag == 'condition':
			condition=element.attrib['data']
		elif element.tag == 'temp_f':
  			ftemp=element.attrib['data']
		elif element.tag == 'humidity':
  			humidity=element.attrib['data']
		elif element.tag == 'wind_condition':
			wind=element.attrib['data']
		#elif element.tag == 'icon' and download:
 		#	icon_download(element.attrib['data'])
 	return "Currently: %s\nTemp: %s\n%s\n%s\n" % (condition, ftemp, humidity, wind)		 



if __name__=="__main__":

	Usage='%prog [ -a | -d | -f | -l | -p | -s ] -z zipcode\n \
		Example: weather_query.py -d -p ~/weather.gif -z 12543'	
	p=optparse.OptionParser(usage=Usage)
	p.add_option('--all', '-a', help='Long listing of the current weather forecast (Default)', action="store_true")
	p.add_option('--data', '-d', help='List the current days data minus location - Geektool', action="store_true")
	p.add_option('--forecast', '-f', help='List the four day forecast', action="store_true")
	p.add_option('--location', '-l', help='List location (Weather status for City,ST:) - Geektool', action="store_true")
	p.add_option('--picture', '-p', help='Local filename to download the current weather icon as - Example: ~/weather.gif', action="store")
	p.add_option('--short', '-s', help='Short listing of the current days weather data', action="store_true")
	p.add_option('--zipcode', '-z', help='5 digit US zipcode', action="store")
	
	(options, args)=p.parse_args()

	###Make sure that we were passed a zipcode option and that it's properly formatted###
	zipregex=re.compile(r'\d{5}')
	try:
	    if zipregex.match(options.zipcode):
		myurl="http://www.google.com/ig/api?weather=%s" % options.zipcode
	    else:
	        p.print_help()
	        sys.exit(1)
	except TypeError:
	    p.print_help()
	    sys.exit(1)

	###Our element tree to parse###
	tree=et.parse(urllib2.urlopen(myurl))

	###if we're passed -p download the current weather status icon as options.picture###	
	if options.picture:
  		icon_download(tree, options.picture)

	###Parse other arguments
	if options.location: 
		print header(tree) 
	elif options.data:
		print current_condition(tree)
        elif options.forecast:
		for i in four_day_forecast(tree):
			print i
	elif options.short:
		print "\n" + header(tree)
		print current_condition(tree)
	else:
		print "\n" + header(tree)
		print current_condition(tree)
		for i in four_day_forecast(tree):
                        print i

